#!/usr/bin/python3
import os
import re
import subprocess
import sys
import time


def opennewfile(Firstcode):
    global WORK_DIR
    #读取工作目录下的pkglist文件，并输出为一个二维数组
    nowfile=open(WORK_DIR+Firstcode+"/"+Firstcode+"_pkglist",'r+')
    #读取文件,pkglist每列记录一个包
    pkglist=nowfile.readlines() 
    for i in range(len(pkglist)):
        pkglist[i]=pkglist[i].split()
    nowfile.close()
    
    print("\n本组名:"+Firstcode+" 总包数："+str(len(pkglist))+"    fedora version:"+pkglist[0][1]+"\n\n")
    return pkglist

def writeresultfile(Firstcode,pkglist):
    global WORK_DIR
    resultfile=open(WORK_DIR+Firstcode+"/"+Firstcode+"_resultlist",'w')
    for line in pkglist :
        if (line[2]=="Waiting"):
            if len(line)>=4:
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+line[3]+"\n")
            else :
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+"\n") 

    for line in pkglist :
        if (line[2]=="success"):
            if len(line)>=4:
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+line[3]+"\n")
            else :
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+"\n")
    for line in pkglist :
        if (line[2]=="incomplete"):
            if len(line)>=4:
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+line[3]+"\n")
            else :
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+"\n")
    for line in pkglist :
        if (line[2]=="failed"):
            if len(line)>=4:
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+line[3]+"\n")
            else :
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+"\n") 
    for line in pkglist :
        if (line[2]=="timeout"):
            if len(line)>=4:
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+line[3]+"\n")
            else :
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+"\n") 

    for line in pkglist :
        if (line[1]=="submit"):
            if len(line)>=4:
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+line[3]+"\n")
            else :
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+"\n") 

    for line in pkglist :
        if line[2] not in ["Waiting","success","incomplete","failed","timeout"]:
            if len(line)>=4:
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+line[3]+"\n")
            else :
                resultfile.write(line[0]+(60-len(line[0]))*" "+line[1]+(15-len(line[1]))*" "+line[2]+(20-len(line[2]))*" "+"\n") 

    resultfile.close()
    return


WORK_DIR=""
if __name__ == "__main__":
    

    #job对应pkg在list里的位置
    Testing_job_number=[]
    Testing_job_ID=[]
    #Testing_job_group=[]
    pkglist=[]

    print("请先执行getpkglsit,输入任意键继续")
    tmp=input()

    print("输入最大同时执行的job数:1~15")
    tmp=input()

    MAX_JOB=7

    tmplist=[]
    for i in range(15):
        tmplist.append(str(i+1))
    if tmp in tmplist:
        MAX_JOB=int(tmp)
    print("最大同时的任务数:"+str(MAX_JOB))

    print("FEDORA_VERSION:")

    REPO_ADDR="https://mirrors.163.com/fedora/releases/36/Everything/source/tree/Packages/"
    print("输入你想构建的包组名，可选的包有：输入*构建所有包")

    pkggroup=["0","2","3","4","5","6","7","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

    Firstcodelisttmp= input().split()  
    Firstcodelist=[]

    if Firstcodelisttmp==["*"] :
        Firstcodelist=pkggroup
    else:
        for i in range(len(Firstcodelisttmp)):
            if Firstcodelisttmp[i]  in pkggroup :
                Firstcodelist.append(Firstcodelisttmp[i])


    print("选中的包组:",Firstcodelist)
    if (Firstcodelist)==[]:
        print("无可用包组，退出程序")
        exit()
    #生成包组列表
    Firstcode=Firstcodelist[0]

    WORK_DIR=subprocess.run(["pwd"],stdout=subprocess.PIPE,encoding="utf-8").stdout

    WORK_DIR=WORK_DIR[0:len(WORK_DIR)-len("autotools/")]
    WORK_DIR=WORK_DIR[0:len(WORK_DIR)]
    #初始化

    print("模板:"+"auto_repoaddr.yaml")



    pkglist=opennewfile(Firstcode)
    HEAD=-1
    #验证无误
    successnum=0
    starttime = time.perf_counter()

    groupinfofile=open(WORK_DIR+"Grouplist","w")

    groupinfofile.write("包组名"+"           "+"成功个数/总数\n"+"----------------------\n")
    groupinfofile.write(Firstcode+(20-len(Firstcode))*" ")
    while(1):

#       command=subprocess.run(["cci","jobs"],stdout=subprocess.PIPE,encoding="utf-8")
#       joblistlines=command.stdout.splitlines()

        #生成此次查询的jobinfo列表，查找testing中的job
#       for line in joblistlines:
        searchtime=0
        position=0
        while(searchtime<len(Testing_job_ID)):
            if (searchtime==0):
                print("查询中")
            searchtime=searchtime+1
        
            
            command=subprocess.run(["sh",WORK_DIR+"autotools/search.sh",Testing_job_ID[position]],stdout=subprocess.PIPE,encoding="utf-8")
            jobinfo=command.stdout.split()

            #每行切割，查找关键字
#           
            #查找到testing中的job
            
            #选中job在当前testing列里的位置——position

            #jobgroup=Testing_job_group[position]
            print(jobinfo[0]+"     "+jobinfo[1]+" "*(15-len(jobinfo[1]))+pkglist[Testing_job_number[position]][0]) 
            #找到测试中的job id，检查状态
            
            if jobinfo[1] in ["finish","submit"]:
                #处于结束状态，更新状态，记录id
                if jobinfo[1]=="submit" :
                    pkglist[Testing_job_number[position]][2]="submit"
                    pkglist[Testing_job_number[position]].append(jobinfo[0])
                    print("检测到ID:"+jobinfo[0]+" JOB已经结束,结果为:"+jobinfo[2])
                    subprocess.run(["cancel",jobinfo[0]])
                
                else :
                    if jobinfo[2]=="success":
                        successnum=successnum+1
                    pkglist[Testing_job_number[position]][2]=jobinfo[2]
                    pkglist[Testing_job_number[position]].append(jobinfo[0])
                    print("检测到ID:"+jobinfo[0]+" JOB已经结束,结果为:"+jobinfo[2])
                
                #并将job从Testing列表中移除
                Testing_job_number.pop(position)
                Testing_job_ID.pop(position)

                #添加新的job,记录id和序号（位置）
                
                #确定已经没有testing job,本组工作做完
                if len(Testing_job_ID)==0 and HEAD==len(pkglist)-1:
                    writeresultfile(Firstcode,pkglist)
                    print("本组所有任务完成，包总数为:"+str(len(pkglist))+" 本次执行成功个数为:"+str(successnum))
                    groupinfofile.write(str(successnum)+"/"+str(len(pkglist))+"\n")
                    groupinfofile.close()
                    
                    #还有新group，打开
                    if Firstcodelist.index(Firstcode)+1<len(Firstcodelist) :
                        #更新firstcode HEAD successnum
                        Firstcode=Firstcodelist[Firstcodelist.index(Firstcode)+1]
                        groupinfofile=open(WORK_DIR+"Grouplist","a")
                        groupinfofile.write(Firstcode+(20-len(Firstcode))*" ")
                        pkglist=opennewfile(Firstcode)
                        HEAD=-1
                        successnum=0
                    else :
                        print("所有组任务都完成,结果输出至Grouplist\n")
                        
                        subprocess.run(["cat",WORK_DIR+"Grouplist"])
                        exit()
                continue
            
            position=position+1
        #寻找下一个job

        if len(Testing_job_ID)<MAX_JOB and HEAD<len(pkglist)-1:
            for i in range(MAX_JOB-len(Testing_job_ID)):
                if HEAD<len(pkglist)-1:
                    
                    HEAD=HEAD+1

                    #只对waiting状态的包submit 不会更改已经是结束状态的包
                    if pkglist[HEAD][2] == "Waiting" or pkglist[HEAD][2] == "timeout" :
                        Testing_job_number.append(HEAD)
                        #Testing_job_group.append(pkglist[HEAD])
                        commandnew=subprocess.run(["submit",WORK_DIR+"autotools/auto_repoaddr.yaml","repo_addr="+REPO_ADDR+Firstcode+"/"+pkglist[HEAD][0]+"."+pkglist[HEAD][1]+".src.rpm"],stdout=subprocess.PIPE,encoding="utf-8")
                        Testing_job_ID.append(commandnew.stdout.split()[len(commandnew.stdout.split())-1][3:])
                        print("----提交新Job:"+commandnew.stdout.split()[len(commandnew.stdout.split())-1][3:]+" ------ "+pkglist[HEAD][0])
                    else :
                        
                        print("跳过Job:   "+pkglist[HEAD][0]+"   原因:"+pkglist[HEAD][2])


        prograssbar="*"*int((HEAD-len(Testing_job_ID)+1)/len(pkglist)*50)+"-"*(50-int((HEAD-len(Testing_job_ID)+1)/len(pkglist)*50))
        print(prograssbar)
        print("当前进度:"+str(HEAD-len(Testing_job_ID)+1)+"/"+str(len(pkglist))+" 正在进行的JOB:"+str(len(Testing_job_ID)))
        print("已执行时间："+str(int((time.perf_counter()-starttime)/60))+" min"+"\n\n")
        
        time.sleep(5)

    writeresultfile(Firstcode,pkglist)
    print("所有任务完成，包总数为:"+str(len(pkglist))+" 本次执行成功个数为:"+str(successnum))
